package com.example.common.utils.result;

import lombok.Data;
import lombok.experimental.Accessors;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * <p>
 * 结合ApiTemplate模板模式
 * </p>
 *
 * @author 12071
 * @date 2022/8/9 22:42
 */
@Data
@Accessors(chain = true)
public class BaseResponse<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final String SUCCESS_CODE = "0";
    private static final String SUCCESS_MSG = "success";
    private static final String FAIL_CODE = "-1";
    private static final String FAIL_MSG = "fail";
    public static final String REQUEST_ID = "requestId";

    private Boolean success;

    private String errorCode;

    private String errorMsg;

    private String requestId;

    private T data;

    public BaseResponse() {
        this.errorCode = SUCCESS_CODE;
        this.errorMsg = SUCCESS_MSG;
        this.requestId = MDC.get(REQUEST_ID);
        this.success = true;
    }

    public BaseResponse(String errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.requestId = MDC.get(REQUEST_ID);
        this.success = false;
    }

    public BaseResponse(String errorCode, T data, boolean success) {
        this.errorCode = errorCode;
        this.requestId = MDC.get(REQUEST_ID);
        this.data = data;
        this.success = success;
    }

    public static <T> BaseResponse<T> ok(T data) {
        return new BaseResponse<T>().setData(data);
    }

    public static <T> BaseResponse<T> ok() {
        return new BaseResponse<>();
    }

    public static <T> BaseResponse<T> fail() {
        return new BaseResponse<>(FAIL_CODE, FAIL_MSG);
    }

    public static <T> BaseResponse<T> fail(String errorCode, String errorMsg) {
        return new BaseResponse<>(errorCode, errorMsg);
    }

    public static <T> BaseResponse<T> fail(String errorMsg) {
        return new BaseResponse<>(FAIL_CODE, errorMsg);
    }

}
